import { apiUrl } from "../../api.js";
import { StorageKeys } from "../../api.js";

// var apiUrl = require('../../api.js');
const $api = require('../../utils/request.js');

const app = getApp();
Page({
  data: {
    name: '',
    quantity: 9,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    categoryIndex: null,
    locationIndex: null,
    imageList: [],
    categoryList: [],
    locationList: [],
    itemDescription: '',
    date: '2022-05-01',

    index: null,
    picker: ['喵喵喵', '汪汪汪', '哼唧哼唧'],
    multiArray: [
      ['无脊柱动物', '脊柱动物'],
      ['扁性动物', '线形动物', '环节动物', '软体动物', '节肢动物'],
      ['猪肉绦虫', '吸血虫']
    ],
    objectMultiArray: [
      [{
        id: 0,
        name: '无脊柱动物'
      },
      {
        id: 1,
        name: '脊柱动物'
      }
      ],
      [{
        id: 0,
        name: '扁性动物'
      },
      {
        id: 1,
        name: '线形动物'
      },
      {
        id: 2,
        name: '环节动物'
      },
      {
        id: 3,
        name: '软体动物'
      },
      {
        id: 3,
        name: '节肢动物'
      }
      ],
      [{
        id: 0,
        name: '猪肉绦虫'
      },
      {
        id: 1,
        name: '吸血虫'
      }
      ]
    ],
    multiIndex: [0, 0, 0],
    time: '12:01',
    region: ['广东省', '广州市', '海珠区'],
    imgList: [],
    modalName: null,
    textareaAValue: '',
    textareaBValue: ''
  },
  onShow() {
    this.setData({
      date: this.formatDate(new Date()),
      categoryList: wx.getStorageSync(StorageKeys.CATEGORY_LIST).list,
      locationList: wx.getStorageSync(StorageKeys.LOCATION_LIST).list,
    })
    console.log(this.data.locationList)
  },
  onLoad() {
    // this.setData({
    //   name: app.globalData.userInfo.nickName
    // })
  },
  formatDate(date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
  },
  handleFormSubmit() {
    // 1 获取文本域的内容 图片数组
    const { textVal, chooseImgs } = this.data;
    // 2 合法性的验证
    if (!textVal.trim()) {
      // 不合法
      wx.showToast({
        title: '输入不合法',
        icon: 'none',
        mask: true
      });
      return;
    }
    // 3 准备上传图片 到专门的图片服务器 
    // 上传文件的 api 不支持 多个文件同时上传  遍历数组 挨个上传 
    // 显示正在等待的图片
    wx.showLoading({
      title: "正在上传中",
      mask: true
    });

    // 判断有没有需要上传的图片数组

    console.log(1);

    if (chooseImgs.length != 0) {
      chooseImgs.forEach((v, i) => {
        wx.uploadFile({
          // 图片要上传到哪里
          url: 'https://images.ac.cn/Home/Index/UploadAction/',
          // 被上传的文件的路径
          filePath: v,
          // 上传的文件的名称 后台来获取文件  file
          name: "file",
          // 顺带的文本信息
          formData: {},
          success: (result) => {
            console.log(result);
            let url = JSON.parse(result.data).url;
            this.UpLoadImgs.push(url);

            // 所有的图片都上传完毕了才触发  
            if (i === chooseImgs.length - 1) {

              wx.hideLoading();


              console.log("把文本的内容和外网的图片数组 提交到后台中");
              //  提交都成功了
              // 重置页面
              this.setData({
                textVal: "",
                chooseImgs: []
              })
              // 返回上一个页面
              wx.navigateBack({
                delta: 1
              });

            }
          }
        });
      })
    } else {
      wx.hideLoading();

      console.log("只是提交了文本");
      wx.navigateBack({
        delta: 1
      });

    }
  },
  LocationChange(e) {
    this.setData({
      locationIndex: e.detail.value,
    })
  },
  CategoryChange(e) {
    this.setData({
      categoryIndex: e.detail.value,
    })
  },
  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value,
      locationIndex: e.detail.value,
    })
  },
  MultiChange(e) {
    this.setData({
      multiIndex: e.detail.value
    })
  },
  MultiColumnChange(e) {
    let data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = ['扁性动物', '线形动物', '环节动物', '软体动物', '节肢动物'];
            data.multiArray[2] = ['猪肉绦虫', '吸血虫'];
            break;
          case 1:
            data.multiArray[1] = ['鱼', '两栖动物', '爬行动物'];
            data.multiArray[2] = ['鲫鱼', '带鱼'];
            break;
        }
        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        break;
      case 1:
        switch (data.multiIndex[0]) {
          case 0:
            switch (data.multiIndex[1]) {
              case 0:
                data.multiArray[2] = ['猪肉绦虫', '吸血虫'];
                break;
              case 1:
                data.multiArray[2] = ['蛔虫'];
                break;
              case 2:
                data.multiArray[2] = ['蚂蚁', '蚂蟥'];
                break;
              case 3:
                data.multiArray[2] = ['河蚌', '蜗牛', '蛞蝓'];
                break;
              case 4:
                data.multiArray[2] = ['昆虫', '甲壳动物', '蛛形动物', '多足动物'];
                break;
            }
            break;
          case 1:
            switch (data.multiIndex[1]) {
              case 0:
                data.multiArray[2] = ['鲫鱼', '带鱼'];
                break;
              case 1:
                data.multiArray[2] = ['青蛙', '娃娃鱼'];
                break;
              case 2:
                data.multiArray[2] = ['蜥蜴', '龟', '壁虎'];
                break;
            }
            break;
        }
        data.multiIndex[2] = 0;
        break;
    }
    this.setData(data);
  },
  TimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },
  RegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['compressed'],//sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
        //TODO FOREACH         
        res.tempFilePaths.forEach((v, i) => {
          this.UploadFile(v)
        })
      }
    });
  },

  // 上传图片
  UploadFile(tempFilePath) {
    console.log(tempFilePath)
    wx.uploadFile({
      header: {
        memberId: wx.getStorageSync(StorageKeys.TOKEN)
      },  // token
      url: apiUrl + '/upload/uploadFile',  // 上传的路径
      filePath: tempFilePath,
      name: 'file',
      formData: {
      },
      success: (uploadFileRes) => {
        let fileData = JSON.parse(uploadFileRes.data)
        console.log("返回值 => " + uploadFileRes.data)
        if (fileData.code == 1) {
          console.log('fileData.data', fileData.data)
          this.data.imageList.push(fileData.data)
          console.log('this.data.imageList', this.data.imageList)
          //  this.data.imageList[i].images.push(fileData.data) //本地查看
          // this.setData({
          //   imageList: this.data.imageList
          // })
        }
      },
      fail(res) {
        console.log(res)
      },
      complete(res) {
        //console.log(res)
      }
    });
  },

  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },

  DelImg(e) {
    wx.showModal({
      title: '召唤师',
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  textareaAInput(e) {
    this.setData({
      itemDescription: e.detail.value
    })
  },
  textareaBInput(e) {
    this.setData({
      textareaBValue: e.detail.value
    })
  },

  inputBlur: function (e) {
    // console.log(JSON.stringify(e));
    var name = e.currentTarget.dataset.name;
    var value = e.detail.value;
    //var data = '{"form":{"' + name + '":"' + value + '"}}';
    var data = '{"' + name + '":"' + value + '"}';
    this.setData(JSON.parse(data));
  },

  save: function () {
    if (this.data.categoryIndex == null) {
      wx.showToast({
        title: '请选择分类',
        icon: 'none',
        mask: true
      });
      return;
    };
    if (this.data.locationIndex == null) {
      wx.showToast({
        title: '请选择位置',
        icon: 'none',
        mask: true
      });
      return;
    };

    // 2 合法性的验证
    if (this.data.name.length > 10) {
      // 不合法
      wx.showToast({
        title: '名称最多10个字',
        icon: 'none',
        mask: true
      });
      return;
    };

    // 2 合法性的验证
    if (this.data.itemDescription.length > 100) {
      // 不合法
      wx.showToast({
        title: '详细描述 最多100个字',
        icon: 'none',
        mask: true
      });
      return;
    };

    // 3 准备上传图片 到专门的图片服务器 
    // 上传文件的 api 不支持 多个文件同时上传  遍历数组 挨个上传 
    // 显示正在等待的图片
    wx.showLoading({
      title: "正在提交",
      mask: true
    });
    var obj = {
      memberId: wx.getStorageSync(StorageKeys.TOKEN),
      nickName: wx.getStorageSync(StorageKeys.USERINFO).nickName,
      categoryId: this.data.categoryList[this.data.categoryIndex].id,
      categoryName: this.data.categoryList[this.data.categoryIndex].categoryName,
      locationId: this.data.locationList[this.data.locationIndex].id,
      locationName: this.data.locationList[this.data.locationIndex].locationName,
      itemName: this.data.name,
      itemImageList: this.data.imageList,
      itemDescription: this.data.itemDescription,
      expireTime: this.data.date + " 00:00:00"
    };
    //调用接口获取openid
    $api.post(apiUrl + '/locker/save', obj)
      .then(res => {
        //请求成功   
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '保存成功，可继续添加', //'这是一个模态弹窗',  
          showCancel: false,
          success(res) {
            if (res.confirm) {

            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        });
        console.log(888)
        this.setData({
          name: '',
          imgList: [],
          itemDescription: '',
        })
      })
      .catch(err => {
        wx.showModal({
          title: '提示',
          content: err,//'这是一个模态弹窗',
          showCancel: false,
        })
        wx.hideLoading();
      })
  }
})